<script setup>
import { computed, ref } from 'vue'
import dayjs from 'dayjs'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'

// 外部属性
const props = defineProps({
  highlightedDates: {
    type: Array,
    default: () => [],
  },
})
dayjs.extend(isSameOrBefore)
dayjs.extend(isSameOrAfter)

// 当前日期
const currentDate = ref(dayjs())
// 是否展开（月视图）
const isExpanded = ref(false)
// 选中的日期
const selectedDate = ref(null)

// 自定义红点日期
const redDotDates = ref([dayjs().add(2, 'day').format('YYYY-MM-DD'), dayjs().add(5, 'day').format('YYYY-MM-DD')])

// 星期（从周一开始）
const weekdays = ['一', '二', '三', '四', '五', '六', '日']

// 上一个月/周
const prev = () => {
  currentDate.value = currentDate.value.subtract(isExpanded.value ? 1 : 1, 'week')
}

// 下一个月/周
const next = () => {
  currentDate.value = currentDate.value.add(isExpanded.value ? 1 : 1, 'week')
}

// 获取当前显示的日期范围
const visibleDays = computed(() => {
  if (isExpanded.value) {
    // 月视图
    const startOfMonth = currentDate.value.startOf('month')
    const startDay = startOfMonth.day() === 0 ? 6 : startOfMonth.day() - 1 // 从周一开始
    const daysInMonth = currentDate.value.daysInMonth()

    const days = []
    for (let i = 0; i < startDay; i++) {
      days.push({ date: startOfMonth.subtract(startDay - i, 'day'), isCurrentMonth: false })
    }
    for (let i = 1; i <= daysInMonth; i++) {
      days.push({ date: startOfMonth.date(i), isCurrentMonth: true })
    }
    const totalDays = days.length
    const remainingDays = 42 - totalDays // 6行 x 7天
    for (let i = 1; i <= remainingDays; i++) {
      days.push({ date: startOfMonth.add(daysInMonth + i - 1, 'day'), isCurrentMonth: false })
    }
    return days
  } else {
    // 周视图
    const startOfWeek = currentDate.value.startOf('week').add(1, 'day') // 从周一开始
    const days = []
    for (let i = 0; i < 7; i++) {
      days.push({ date: startOfWeek.add(i, 'day'), isCurrentMonth: true })
    }
    return days
  }
})

// 判断是否是今天
const isToday = (date) => {
  return dayjs().isSame(date, 'day')
}

// 判断是否选中
const isSelected = (date) => {
  return selectedDate.value && dayjs(selectedDate.value).isSame(date, 'day')
}

// 判断是否有红点
const hasRedDot = (date) => {
  return redDotDates.value.includes(date.format('YYYY-MM-DD'))
}

// 判断是否高亮
const isHighlighted = (date) => {
  return props.highlightedDates.includes(date.format('YYYY-MM-DD'))
}

// 选择日期
const selectDate = (date) => {
  selectedDate.value = date
  console.log('选择的日期:', date.format('YYYY-MM-DD'))
}

// 切换展开/收起
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}
</script>

<template>
  <div class="calendar">
    <!-- 日历头部 -->
    <div class="calendar-header">
      <button @click="prev">
        &lt;
      </button>
      <span>{{ currentDate.format("YYYY年MM月") }}</span>
      <button @click="next">
        &gt;
      </button>
    </div>

    <!-- 日历内容 -->
    <div class="calendar-body">
      <!-- 星期 -->
      <div class="weekdays">
        <div v-for="day in weekdays" :key="day" class="weekday">
          {{ day }}
        </div>
      </div>

      <!-- 日期 -->
      <div class="days">
        <div
          v-for="(day, index) in visibleDays"
          :key="index"
          class="day"
          :class="[
            {
              'current-month': day.isCurrentMonth,
              'selected': isSelected(day.date),
              'highlighted': isHighlighted(day.date),
              'today': isToday(day.date),
            },
          ]"
          @click="selectDate(day.date)"
        >
          {{ day.date.date() }}
          <span v-if="hasRedDot(day.date)" class="red-dot" />
        </div>
      </div>
    </div>

    <!-- 展开/收起按钮 -->
    <div class="toggle-button" @click="toggleExpand">
      {{ isExpanded ? "收起" : "展开" }}
    </div>
  </div>
</template>

<style scoped>
.calendar {
  font-family: Arial, sans-serif;
  max-width: 400px;
  margin: 0 auto;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.calendar-header button {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
}

.weekdays {
  display: flex;
  justify-content: space-around;
  margin-bottom: 8px;
  font-weight: bold;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8px;
}

.day {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
}

.day.current-month {
  color: #000;
}

.day:not(.current-month) {
  color: #ccc;
}

.day.today {
  background: #e0f7fa;
}

.day.selected {
  background: #007bff;
  color: #fff;
}

.day.highlighted {
  background: #ffeb3b;
}

.red-dot {
  position: absolute;
  bottom: 4px;
  width: 6px;
  height: 6px;
  background: red;
  border-radius: 50%;
}

.toggle-button {
  margin-top: 16px;
  text-align: center;
  padding: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
}

.toggle-button:hover {
  background: #e0e0e0;
}
</style>
